<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Menu;
use Symfony\Component\HttpKernel\Exception\HttpException;

class MenuController extends Controller
{
    // 初始化保存模型
    protected function initialize()
    {
        $this->model = new Menu();
    }

    public function index()
    {

        $list = $this->model::all();

        $squared = array_map(function ($item) {
            $item['fixedTag'] = (bool)$item['fixedTag'];
            $item['hiddenTag'] = (bool)$item['hiddenTag'];
            $item['keepAlive'] = (bool)$item['keepAlive'];
            $item['showLink'] = (bool)$item['showLink'];
            $item['showParent'] = (bool)$item['showParent'];
            $item['frameLoading'] = (bool)$item['frameLoading'];

            // 将数据库为 null 的值转换为空字符串
            foreach ($item as $key => $value) {
                if ($value === null) {
                    $item[$key] = '';
                }
            }

            return $item;
        },  $list->toArray());

        return $this->success(message: '获取成功', data: $squared);
    }

    public function store(Request $request)
    {
        $body = $request->json()->all();

        try {
            $model = $this->model::create($body);
            return $this->success(data: ['id' => $model->id]);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function update($id, Request $request)
    {
        $body = $request->json()->all();
        try {
            $this->model::where('id', $id)->update($body);
            return $this->success(message: '修改成功');
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function destroy($id)
    {
        try {
            $this->model::destroy($id);
            return $this->success(message: '删除成功');
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }
}
